package com.zhoutao.blog.seven.service.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.zhoutao.blog.seven.dao.model.SettingDao;
import com.zhoutao.blog.seven.dao.repository.SettingRepository;
import com.zhoutao.blog.seven.model.Cacheable;
import com.zhoutao.blog.seven.model.converter.SettingConverter;
import com.zhoutao.blog.seven.model.response.Setting;
import com.zhoutao.blog.seven.service.SettingService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class SettingServiceImpl implements SettingService, Cacheable {

    private final SettingRepository settingRepository;

    private final SettingConverter settingConverter;

    private Cache<String, Map<String, String>> CACHE =
            CacheBuilder.newBuilder()
                    .expireAfterWrite(1, TimeUnit.MINUTES)
                    .build();

    @Override
    @SneakyThrows
    public Map<String, String> findConfigByKeyWithCache(String... key) {
        return CACHE.get("ALL", () -> findConfigByKey(key));
    }

    @Override
    public Map<String, String> findConfigByKey(String... key) {
        List<SettingDao> settingDaoList = settingRepository.listByKey(Arrays.asList(key));
        return settingDaoList.stream()
                .map(settingConverter::converterFrom)
                .collect(Collectors.toMap(Setting::getKeyName, Setting::getValue, (v1, v2) -> v1));
    }

    @Override
    public void cleanCache() {
        this.CACHE.invalidateAll();
    }
}
